﻿using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using System.Windows.Media.Imaging;
using System.Windows;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.UI.Events;
using MainFamilyViewWindow = ZhuXingFamilys.MainFamilyView.MainFamilyView;
using ZhuXingFamilys.User;
using Autodesk.Revit.DB.Events;
using System.Runtime.InteropServices;
using ZhuXingFamilys.MainFamilyView;
using ZhuXingFamilys.ExportExcel;
using ZhuXingFamilys.Help;
using System.IO;
using System.Diagnostics;
using TextBox = Autodesk.Revit.UI.TextBox;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using System.Web.UI.WebControls;
using ZhuXingFamilys.utils;
using System.Net;
using System.Reflection;

namespace ZhuXingFamilys
{
    [Transaction(TransactionMode.Manual)]
    public class CsAddpanel : IExternalApplication
    {

        //private static String addinAssmeblyPath = typeof(CsAddpanel).Assembly.Location;
        string addinAssmeblyPath = Assembly.GetExecutingAssembly().Location;



        private LoadFamily loadFamily = null;
        private ExternalEvent LoadFamilyEvent = null;
        // 是否加载族库
        private bool isZuKuInstall = false;
        // 是否加载雁伴
        private bool isYanBanInstall = false;
        private UIControlledApplication UIapp;

        public Result OnShutdown(UIControlledApplication application)
        {
            return Result.Succeeded;
        }

        public Result OnStartup(UIControlledApplication application)
        {
            this.UIapp = application;
            // 读取配置
            getPluginConfig();

            s_uiApplication = application;
            ApplicationOptions.Initialize(this);

            createCommandBinding(application);
            createRibbonButton(application);

            // “修改”选项卡下按钮
            //changeModify(application);
            // 注册可停靠窗口
            //regionDockablePane(application);


            // add custom tabs to options dialog.
            AddTabCommand addTabCommand = new AddTabCommand(application);
            addTabCommand.AddTabToOptionsDialog();

            // 注册文档变化事件
            application.ControlledApplication.DocumentChanged
                += ControlledApplication_DocumentChanged;
            // 注册文档激活事件
            application.ViewActivated += Application_ViewActivated;
            // 注册检查用户事件
            application.Idling += userCheck;
            // 注册Revit关闭事件
            application.ApplicationClosing += Application_ApplicationClosing;
            return Result.Succeeded;
        }

        public const string CONFIG_LOGIN_CONTENT = "LoginInfo";
        public const string CONFIG_LOGIN_LOGINTIME_CONTENT = "LoginTime";
        public const string CONFIG_LOGIN_IsRemember_CONTENT = "IsRemember";
        public const string CONFIG_LOGIN_Authority_CONTENT = "Authority";
        // Revit关闭事件
        private void Application_ApplicationClosing(object sender, ApplicationClosingEventArgs e)
        {
            // 如果没有记住密码 退出登录
            string iniFilePath = "LoginInfo.ini";
            string CurAppDir = Set.getaddress();
            //配置文件路径是相对路径则需加上当前exe所在路径作为根路径
            if (!iniFilePath.Contains("\\") || !Path.IsPathRooted(iniFilePath))
            {
                iniFilePath = Path.Combine(CurAppDir, iniFilePath);
            }
            Set.GetValue(CONFIG_LOGIN_CONTENT, CONFIG_LOGIN_IsRemember_CONTENT, iniFilePath, out string Irvalue);
            if (!Convert.ToBoolean(Irvalue))
            {
                UserCenter.LogOut();
            }
        }

        // 检查用户
        private void userCheck(object sender, IdlingEventArgs e)
        {
            string iniFilePath = "LoginInfo.ini";
            string CurAppDir = Set.getaddress();
            long time = 172801;
            //配置文件路径是相对路径则需加上当前exe所在路径作为根路径
            if (!iniFilePath.Contains("\\") || !Path.IsPathRooted(iniFilePath))
            {
                iniFilePath = Path.Combine(CurAppDir, iniFilePath);
            }
            Set.GetValue(CONFIG_LOGIN_CONTENT, CONFIG_LOGIN_LOGINTIME_CONTENT, iniFilePath, out string ctimevalue);
            Set.GetValue(CONFIG_LOGIN_CONTENT, CONFIG_LOGIN_IsRemember_CONTENT, iniFilePath, out string IsRemember);
            Set.GetValue(CONFIG_LOGIN_CONTENT, CONFIG_LOGIN_Authority_CONTENT, iniFilePath, out string Authority);

            if (!string.IsNullOrEmpty(ctimevalue) && !string.IsNullOrEmpty(IsRemember) && !string.IsNullOrEmpty(Authority) && Convert.ToBoolean(IsRemember))
            {
                if (DateTime.TryParse(ctimevalue, out DateTime dtDate))
                {
                    long loginTicks = TimeUtils.GetTimeStamp(dtDate);
                    long nowTicks = TimeUtils.GetTimeStamp(DateTime.Now);
                    time = nowTicks - loginTicks;
                }
                if (time > 172800)
                {
                    UserCenter.LogOut();
                }
                else
                {
                    // 根据权限启用Panel
                    if (int.TryParse(Authority, out int cheint))
                    {
                        PanelEnableDisableUtils.CheckAuthority(cheint);
                    }
                }
            }
            else
            {
                UserCenter.LogOut();
            }
            // 检查后注销闲时事件
            UIapp.Idling -= userCheck;
        }
        // 文档激活事件
        private void Application_ViewActivated(object sender, ViewActivatedEventArgs e)
        {
            // 文档激活后自动打开属性面板
            // UIApplication uiapp = sender as UIApplication;
            // string PageGuid = "321044f7-b0b2-4b1c-af18-e71a19252be0";
            // Guid guid = new Guid(PageGuid);
            // DockablePaneId paneId = new DockablePaneId(guid);
            // DockablePane pane = uiapp.GetDockablePane(paneId);
            // if (!pane.IsShown())
            // {
            //     pane.Show();
            // }
        }

        // 读取配置文件
        private void getPluginConfig()
        {
            // 族库配置
            string iniFilePath = "ConfigZK.ini";
            string CurAppDir = Set.getaddress();
            if (!iniFilePath.Contains("\\") || !Path.IsPathRooted(iniFilePath))
            {
                iniFilePath = Path.Combine(CurAppDir, iniFilePath);
            }
            if (File.Exists(iniFilePath))
            {
                isZuKuInstall = true;
            }

            // 雁伴配置
            string iniFilePath1 = "ConfigYB.ini";
            string CurAppDir1 = Set.getaddress();
            if (!iniFilePath1.Contains("\\") || !Path.IsPathRooted(iniFilePath1))
            {
                iniFilePath1 = Path.Combine(CurAppDir1, iniFilePath1);
            }
            if (File.Exists(iniFilePath1))
            {
                isYanBanInstall = true;

            }
        }

        // 注册可停靠窗口
        private void regionDockablePane(UIControlledApplication application)
        {
            // 注册筑星族库属性窗口
            string PageGuid = "321044f7-b0b2-4b1c-af18-e71a19252be0";
            FamilyAttribute attribute = new FamilyAttribute(application);
            Guid guid = new Guid(PageGuid);
            DockablePaneId paneId = new DockablePaneId(guid);
            application.RegisterDockablePane(paneId, "筑星族属性", attribute);

        }

        void createCommandBinding(UIControlledApplication application)
        {
            RevitCommandId wallCreate = RevitCommandId.LookupCommandId("ID_NEW_REVIT_DESIGN_MODEL");

            // RevitCommandId wallCreate = RevitCommandId.LookupCommandId("ID_NEW_REVIT_DESIGN_MODEL_LIU");
            AddInCommandBinding binding = application.CreateAddInCommandBinding(wallCreate);
            binding.Executed += new EventHandler<Autodesk.Revit.UI.Events.ExecutedEventArgs>(binding_Executed);
            binding.CanExecute += new EventHandler<Autodesk.Revit.UI.Events.CanExecuteEventArgs>(binding_CanExecute);
            loadFamily = new LoadFamily();
            LoadFamilyEvent = ExternalEvent.Create(loadFamily);
        }
        //图片转化
        public static BitmapSource convertFromBitmap(System.Drawing.Bitmap bitmap)
        {
            return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                bitmap.GetHbitmap(),
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
        }



        // 创建按钮
        void createRibbonButton(UIControlledApplication application)
        {
            // 加载筑星族库面板
            if (isZuKuInstall)
            {
                //添加一个新的Ribbon 面板
                application.CreateRibbonTab("筑星族库");
                RibbonPanel rp = application.CreateRibbonPanel("筑星族库", "云族库");
                PushButtonData pbdMfv = new PushButtonData("MainFamilyView", "公共族库", addinAssmeblyPath, "ZhuXingFamilys.MainFamilyView.MainFamilyVIewCommand");
                pbdMfv.LargeImage = convertFromBitmap(Properties.Resource.公共族库);
                pbdMfv.Image = convertFromBitmap(Properties.Resource.公共族库);
                PushButton pb5Mfv = rp.AddItem(pbdMfv) as PushButton;
                //实现命令在什么时候可用，禁用的控制
                //pb5Mfv.AvailabilityClassName = "ZhuXingFamilys.ButtonAvailabilityClass";
                TextBoxData pbdSelect = new TextBoxData("pbdSelect");
                pbdSelect.Image = convertFromBitmap(Properties.Resource.技术支持);
                pbdSelect.Name = "pbdSelect";
                pbdSelect.ToolTip = "输入族名称";
                pbdSelect.LongDescription = "<p>可以查询想要查询的族名称关键字，可以模糊查询</p>";
                pbdSelect.ToolTipImage = convertFromBitmap(Properties.Resource.查询);
                pbdSelect.Image = convertFromBitmap(Properties.Resource.查询);
                TextBox pbSelect = rp.AddItem(pbdSelect) as TextBox;
                pbSelect.PromptText = "请输入要查询的关键字";
                pbSelect.ShowImageAsButton = true;
                pbSelect.EnterPressed += new EventHandler<TextBoxEnterPressedEventArgs>(txtBox_EnterPressed);
                //pbSelect.Enabled = UserLoginCommand.TestZKLogincommand();

                RibbonPanel rpMf = application.CreateRibbonPanel("筑星族库", "管理族");
                PushButtonData pbdMfm = new PushButtonData("FileUpload", "上传族", addinAssmeblyPath, "ZhuXingFamilys.Fileupload.FileUploadCommand");
                pbdMfm.LargeImage = convertFromBitmap(Properties.Resource.上传云);
                pbdMfm.Image = convertFromBitmap(Properties.Resource.上传云);
                PushButton pbMfm = rpMf.AddItem(pbdMfm) as PushButton;
                //实现命令在什么时候可用，禁用的控制
                //pbMfm.AvailabilityClassName = "ZhuXingFamilys.ButtonAvailabilityClass";
                PushButtonData pbdfz = new PushButtonData("familyfileconvert", "族文件复制", addinAssmeblyPath, "ZhuXingFamilys.test.FamilyFileConvert_1");
                pbdfz.LargeImage = convertFromBitmap(Properties.Resource.复制);
                pbdfz.Image = convertFromBitmap(Properties.Resource.复制);
                PushButton pbdfzz = rpMf.AddItem(pbdfz) as PushButton;
                //实现命令在什么时候可用，禁用的控制
                //pbdfzz.AvailabilityClassName = "ZhuXingFamilys.ButtonAvailabilityClass";

                RibbonPanel rpHelp = application.CreateRibbonPanel("筑星族库", "帮助");
                PushButtonData pbdAc = new PushButtonData("AuthorizationControl", "授权", addinAssmeblyPath, "ZhuXingFamilys.User.UserLoginCommand");
                pbdAc.LargeImage = convertFromBitmap(Properties.Resource.授权);
                pbdAc.Image = convertFromBitmap(Properties.Resource.授权);
                PushButtonData pbdHc = new PushButtonData("HelpControl", "官方网站", addinAssmeblyPath, "ZhuXingFamilys.Help.OfficialWebsite");
                pbdHc.LargeImage = convertFromBitmap(Properties.Resource.官方网站);
                pbdHc.Image = convertFromBitmap(Properties.Resource.官方网站);
                PushButtonData pbdTeach = new PushButtonData("Teach", "视频教学", addinAssmeblyPath, "ZhuXingFamilys.Help.Teach");
                pbdTeach.LargeImage = convertFromBitmap(Properties.Resource.视频教学);
                pbdTeach.Image = convertFromBitmap(Properties.Resource.视频教学);
                PushButtonData pbdTs = new PushButtonData("TechnicalSupport", "技术支持", addinAssmeblyPath, "ZhuXingFamilys.Help.TechnicalSupport");
                pbdTs.LargeImage = convertFromBitmap(Properties.Resource.技术支持);
                pbdTs.Image = convertFromBitmap(Properties.Resource.技术支持);
                PushButtonData pbdSetting = new PushButtonData("Setting", "设置", addinAssmeblyPath, "ZhuXingFamilys.Help.Setting");
                pbdSetting.LargeImage = convertFromBitmap(Properties.Resource.设置);
                pbdSetting.Image = convertFromBitmap(Properties.Resource.设置);
                PushButtonData pbdUpdate = new PushButtonData("Update", "检查更新", addinAssmeblyPath, "ZhuXingFamilys.Help.Update");
                pbdUpdate.LargeImage = convertFromBitmap(Properties.Resource.检查更新);
                pbdUpdate.Image = convertFromBitmap(Properties.Resource.检查更新);
                PushButtonData pbdAbout = new PushButtonData("About", "关于", addinAssmeblyPath, "ZhuXingFamilys.Help.Abouting");
                pbdAbout.LargeImage = convertFromBitmap(Properties.Resource.关于);
                pbdAbout.Image = convertFromBitmap(Properties.Resource.关于);
                PushButton pbAc = rpHelp.AddItem(pbdAc) as PushButton;
                IList<RibbonItem> listRibbon1 = rpHelp.AddStackedItems(pbdHc, pbdTeach, pbdTs);
                IList<RibbonItem> listRibbon2 = rpHelp.AddStackedItems(pbdSetting, pbdUpdate, pbdAbout);
            }

            // 加载雁伴面板
            if (isYanBanInstall)
            {
                application.CreateRibbonTab("雁伴毕姆信息平台");

                RibbonPanel rpfile = application.CreateRibbonPanel("雁伴毕姆信息平台", "雁伴造价");

                PushButtonData pbdete = new PushButtonData("ExportToExcel", "工程分部分项清单算量", addinAssmeblyPath, "ZhuXingFamilys.ExportExcel.ExportExcelcommand");
                pbdete.LargeImage = convertFromBitmap(Properties.Resource.导出);
                pbdete.Image = convertFromBitmap(Properties.Resource.导出);
                PushButton pbdee = rpfile.AddItem(pbdete) as PushButton;
                //实现命令在什么时候可用，禁用的控制
                //pbdee.AvailabilityClassName = "ZhuXingFamilys.ButtonAvailabilityClassYanban";

                PushButtonData pbdqddb = new PushButtonData("ListComparison", "清单对比", addinAssmeblyPath, "ZhuXingFamilys.ListComparison.ListComparisonCommand");
                pbdqddb.LargeImage = convertFromBitmap(Properties.Resource.清单对比);
                pbdqddb.Image = convertFromBitmap(Properties.Resource.清单对比);
                PushButton pbdqddbb = rpfile.AddItem(pbdqddb) as PushButton;
                //实现命令在什么时候可用，禁用的控制
                //pbdqddbb.AvailabilityClassName = "ZhuXingFamilys.ButtonAvailabilityClassYanban";

                PushButtonData pbdyjfx = new PushButtonData("EarlyWarningAnalysis", "预警分析", addinAssmeblyPath, "ZhuXingFamilys.EarlyWarningAnalysis.EarlyWarningAnalysisCommand");
                pbdyjfx.LargeImage = convertFromBitmap(Properties.Resource.预警分析);
                pbdyjfx.Image = convertFromBitmap(Properties.Resource.预警分析);
                PushButton pbdyjfxb = rpfile.AddItem(pbdyjfx) as PushButton;
                //实现命令在什么时候可用，禁用的控制
                //pbdyjfxb.AvailabilityClassName = "ZhuXingFamilys.ButtonAvailabilityClassYanban";


                RibbonPanel YBXX = application.CreateRibbonPanel("雁伴毕姆信息平台", "雁伴毕姆");

                PushButtonData MXXX = new PushButtonData("ModelInformation", "BIM模型信息提取", addinAssmeblyPath, "ZhuXingFamilys.ModelInformation.ModelInformationCommand");
                MXXX.LargeImage = convertFromBitmap(Properties.Resource.信息);
                MXXX.Image = convertFromBitmap(Properties.Resource.信息);
                PushButton MXXXX = YBXX.AddItem(MXXX) as PushButton;
                //实现命令在什么时候可用，禁用的控制
                //MXXXX.AvailabilityClassName = "ZhuXingFamilys.ButtonAvailabilityClassYanban";

                PushButtonData CADXX = new PushButtonData("CADInformation", "CAD信息提取", addinAssmeblyPath, "ZhuXingFamilys.CADInformation.CADInformationCommand");
                CADXX.LargeImage = convertFromBitmap(Properties.Resource.CAD);
                CADXX.Image = convertFromBitmap(Properties.Resource.CAD);
                PushButton CADXXX = YBXX.AddItem(CADXX) as PushButton;
                //实现命令在什么时候可用，禁用的控制
                //CADXXX.AvailabilityClassName = "ZhuXingFamilys.ButtonAvailabilityClassYanban";

                //PushButtonData SHZB1 = new PushButtonData("AuditIndicators1", "审核指标", addinAssmeblyPath, "ZhuXingFamilys.AuditIndicators.AuditIndicatorsCommand");
                //SHZB1.LargeImage = convertFromBitmap(Properties.Resource.审核);
                //SHZB1.Image = convertFromBitmap(Properties.Resource.审核);
                //PushButton SHZBB1 = YBXX.AddItem(SHZB1) as PushButton;

                PulldownButtonData SHZB = new PulldownButtonData("AuditIndicators", "审核指标");
                SHZB.LargeImage = convertFromBitmap(Properties.Resource.审核);
                SHZB.Image = convertFromBitmap(Properties.Resource.审核);
                PulldownButton SHZBB = YBXX.AddItem(SHZB) as PulldownButton;
                PushButtonData SMYZBT = new PushButtonData("RealAndModel", "实模一致审核", addinAssmeblyPath, "ZhuXingFamilys.AuditIndicators.RealAndModelCommand");
                SMYZBT.LargeImage = convertFromBitmap(Properties.Resource.模型1);
                SMYZBT.Image = convertFromBitmap(Properties.Resource.模型1);
                PushButtonData TMYZBT = new PushButtonData("MapAndModel", "图模一致审核", addinAssmeblyPath, "ZhuXingFamilys.AuditIndicators.MapAndModelCommand");
                TMYZBT.LargeImage = convertFromBitmap(Properties.Resource.模型);
                TMYZBT.Image = convertFromBitmap(Properties.Resource.模型);
                PushButtonData QTSHBT = new PushButtonData("MandatoryProvision", "强条审核", addinAssmeblyPath, "ZhuXingFamilys.AuditIndicators.MandatoryProvisionCommand");
                QTSHBT.LargeImage = convertFromBitmap(Properties.Resource.规范);
                QTSHBT.Image = convertFromBitmap(Properties.Resource.规范);
                SHZBB.AddPushButton(SMYZBT);
                SHZBB.AddPushButton(TMYZBT);
                SHZBB.AddPushButton(QTSHBT);
                //实现命令在什么时候可用，禁用的控制
                //SHZBB.Enabled = UserLoginCommand.TestYanBanLogincommand();
                //SHZBB.AvailabilityClassName = "ZhuXingFamilys.ButtonAvailabilityClassYanban";

                //PushButtonData pbdInfo = new PushButtonData("info", "族属性", addinAssmeblyPath, "ZhuXingFamilys.MainFamilyView.FamilyAttributeCommand");
                //pbdInfo.LargeImage = convertFromBitmap(Properties.Resource.信息);
                //pbdInfo.Image = convertFromBitmap(Properties.Resource.信息);
                //PushButton pbdInfoo = rpMf.AddItem(pbdInfo) as PushButton;
                ////实现命令在什么时候可用，禁用的控制
                //pbdInfo.AvailabilityClassName = "ZhuXingFamilys.ButtonAvailabilityClass";

                RibbonPanel rpHelp1 = application.CreateRibbonPanel("雁伴毕姆信息平台", "帮助");
                PushButtonData pbdAc = new PushButtonData("AuthorizationControl", "授权", addinAssmeblyPath, "ZhuXingFamilys.User.UserLoginCommand");
                pbdAc.LargeImage = convertFromBitmap(Properties.Resource.授权);
                pbdAc.Image = convertFromBitmap(Properties.Resource.授权);
                PushButtonData pbdHc = new PushButtonData("HelpControl", "官方网站", addinAssmeblyPath, "ZhuXingFamilys.Help.OfficialWebsite");
                pbdHc.LargeImage = convertFromBitmap(Properties.Resource.官方网站);
                pbdHc.Image = convertFromBitmap(Properties.Resource.官方网站);
                PushButtonData pbdTeach = new PushButtonData("Teach", "视频教学", addinAssmeblyPath, "ZhuXingFamilys.Help.Teach");
                pbdTeach.LargeImage = convertFromBitmap(Properties.Resource.视频教学);
                pbdTeach.Image = convertFromBitmap(Properties.Resource.视频教学);
                PushButtonData pbdTs = new PushButtonData("TechnicalSupport", "技术支持", addinAssmeblyPath, "ZhuXingFamilys.Help.TechnicalSupport");
                pbdTs.LargeImage = convertFromBitmap(Properties.Resource.技术支持);
                pbdTs.Image = convertFromBitmap(Properties.Resource.技术支持);
                PushButtonData pbdSetting = new PushButtonData("Setting", "设置", addinAssmeblyPath, "ZhuXingFamilys.Help.Setting");
                pbdSetting.LargeImage = convertFromBitmap(Properties.Resource.设置);
                pbdSetting.Image = convertFromBitmap(Properties.Resource.设置);
                PushButtonData pbdUpdate = new PushButtonData("Update", "检查更新", addinAssmeblyPath, "ZhuXingFamilys.Help.Update");
                pbdUpdate.LargeImage = convertFromBitmap(Properties.Resource.检查更新);
                pbdUpdate.Image = convertFromBitmap(Properties.Resource.检查更新);
                PushButtonData pbdAbout = new PushButtonData("About", "关于", addinAssmeblyPath, "ZhuXingFamilys.Help.Abouting");
                pbdAbout.LargeImage = convertFromBitmap(Properties.Resource.关于);
                pbdAbout.Image = convertFromBitmap(Properties.Resource.关于);
                PushButton pbAc = rpHelp1.AddItem(pbdAc) as PushButton;
                IList<RibbonItem> listRibbon1 = rpHelp1.AddStackedItems(pbdHc, pbdTeach, pbdTs);
                IList<RibbonItem> listRibbon2 = rpHelp1.AddStackedItems(pbdSetting, pbdUpdate, pbdAbout);
            }
        }

        // “修改”选项下添加按钮
        private void changeModify(UIControlledApplication application)
        {
            foreach (Autodesk.Windows.RibbonTab tab in Autodesk.Windows.ComponentManager.Ribbon.Tabs)
            {
                if (tab.Id == "Modify")//将按钮嵌入到修改选项卡上
                {
                    Autodesk.Windows.RibbonPanel ADNPanel = new Autodesk.Windows.RibbonPanel();
                    Autodesk.Windows.RibbonPanelSource ADNSource = new Autodesk.Windows.RibbonPanelSource();
                    ADNSource.Id = "ID_NRC_Panel";
                    // ADNSource.Name = "筑星族库";
                    ADNSource.Title = "筑星族库";
                    ADNPanel.Source = ADNSource;

                    //Autodesk.Windows.RibbonButton button = new Autodesk.Windows.RibbonButton();
                    //button.Image = convertFromBitmap(Properties.Resource.文件);
                    //button.LargeImage = convertFromBitmap(Properties.Resource.文件);
                    //button.ShowImage = true;
                    //button.Size = Autodesk.Windows.RibbonItemSize.Large;
                    //button.ShowText = true;
                    //button.Id = "ID_NRC_Button";
                    //// button.Name = "修改";
                    //button.Text = "修改族";
                    //button.IsEnabled = true;
                    //button.IsVisible = true;
                    //button.IsCheckable = true;//如果不设置，则按钮不可用，也不知是否为天生的Bug等有时间再解决喽
                    //button.Orientation = System.Windows.Controls.Orientation.Vertical;

                    Autodesk.Windows.RibbonCombo combo = new Autodesk.Windows.RibbonCombo();
                    //combo.Image = convertFromBitmap(Properties.Resource.文件);
                    //combo.LargeImage = convertFromBitmap(Properties.Resource.文件);
                    combo.ShowImage = false;
                    combo.Size = Autodesk.Windows.RibbonItemSize.Large;
                    combo.ShowText = true;
                    combo.Id = "ID_NRC_Combo";
                    combo.Text = "宽度";
                    combo.IsEnabled = true;
                    combo.IsVisible = true;

                    //ADNPanel.Source.Items.Add(button);
                    ADNPanel.Source.Items.Add(combo);
                    Autodesk.Windows.ComponentManager.UIElementActivated += new EventHandler<Autodesk.Windows.UIElementActivatedEventArgs>(ComponentManager_UIElementActivated);
                    tab.Panels.Add(ADNPanel);

                    break;
                }
            }
        }

        // 按钮触发事件，可以也逻辑代码，允许开启事务
        void ComponentManager_UIElementActivated(object sender, Autodesk.Windows.UIElementActivatedEventArgs e)
        {
            if (e != null && e.Item != null && e.Item.Id != null && e.Item.Id == "ID_NRC_Button")
            {
                try
                {
                    System.Windows.MessageBox.Show("test");
                }
                catch { }
            }

        }


        private void txtBox_EnterPressed(object sender, TextBoxEnterPressedEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            //TaskDialog.Show("TextBox Input", "This is what you typed in: " + textBox.Value.ToString());
            MainFamilyViewWindow mainFamilyViewWindow = new MainFamilyViewWindow(textBox.Value.ToString());
            //将窗口绑定到主窗口之上
            System.Windows.Interop.WindowInteropHelper mainUI = new System.Windows.Interop.WindowInteropHelper(mainFamilyViewWindow);
            mainUI.Owner = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
            mainFamilyViewWindow.Show();
            //MainViewModel form = new MainFamilyView();
            //form.Show();
        }



        public UIControlledApplication UIControlledApplication
        {
            get { return s_uiApplication; }
        }

        private UIControlledApplication s_uiApplication;

        void binding_CanExecute(object sender, Autodesk.Revit.UI.Events.CanExecuteEventArgs e)
        {
            e.CanExecute = true;
        }

        void binding_Executed(object sender, Autodesk.Revit.UI.Events.ExecutedEventArgs e)
        {
            UIApplication uiApp = sender as UIApplication;
            if (uiApp == null)
                return;

            String famTemplatePath = uiApp.Application.FamilyTemplatePath;
            String conceptualmassTemplatePath = famTemplatePath + @"\Conceptual Mass\Mass.rft";
            if (System.IO.File.Exists(conceptualmassTemplatePath))
            {
                //uiApp.OpenAndActivateDocument(conceptualmassTemplatePath);
                Document familyDocument = uiApp.Application.NewFamilyDocument(conceptualmassTemplatePath);
                if (null == familyDocument)
                {
                    throw new Exception("Cannot open family document");
                }

                String fileName = Guid.NewGuid().ToString() + ".rfa";
                familyDocument.SaveAs(fileName);
                familyDocument.Close();

                uiApp.OpenAndActivateDocument(fileName);

                FilteredElementCollector collector = new FilteredElementCollector(uiApp.ActiveUIDocument.Document);
                collector = collector.OfClass(typeof(View3D));

                var query = from element in collector

                            where element.Name == "{3D}"

                            select element; // Linq query  

                List<Element> views = query.ToList();

                View3D view3D = views[0] as View3D;
                if (view3D != null)
                    uiApp.ActiveUIDocument.ActiveView = view3D;
            }
        }
        // 文档发生变化事件
        void ControlledApplication_DocumentChanged(object sender, DocumentChangedEventArgs e)
        {
            Document doc = e.GetDocument(); //获取对应的文档对象
            ICollection<ElementId> added = e.GetAddedElementIds(); //获取增加的对象
            //ICollection<ElementId> deleted = e.GetDeletedElementIds(); //获取删除的对象
            //ICollection<ElementId> modified = e.GetModifiedElementIds(); //获取修改的对象
            foreach (ElementId id in added)
            {
                Element el = doc.GetElement(id);
                if (el.Name.StartsWith("喷浆护壁") && el.GetType() == typeof(FamilyInstance))
                {
                    // 发送虚拟按键 两次esc 用于喷浆护壁结束放置
                    showKey();
                    // 连续放置
                    loadFamily.FamilyFileName = "喷浆护壁";
                    loadFamily.FamilyFileCategory = "1";
                    loadFamily.LoadButtonCont = "放置";
                    LoadFamilyEvent.Raise();
                }
                else if (el.Name.StartsWith("钢筋挂网") && el.GetType() == typeof(FamilyInstance))
                {
                    // 发送虚拟按键 两次esc 用于喷浆护壁结束放置
                    showKey();
                    // 连续放置
                    loadFamily.FamilyFileName = "钢筋挂网";
                    loadFamily.FamilyFileCategory = "1";
                    loadFamily.LoadButtonCont = "放置";
                    LoadFamilyEvent.Raise();
                }
            }
        }

        // 发送两次esc
        [DllImport("user32.dll")]
        internal static extern bool SetForegroundWindow(IntPtr hWnd);
        [DllImport("user32.dll")]
        //第一个值为虚拟键值，第二个参数为扫描不设置为0，第三个数为按键状态选项 keydown为0，如果为keyup 则设置成2，KEYEVENT_KEYUP,第四个参数一般为0
        internal static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
        //写一个方法或是在窗体控件下触发，这里我们发送ESC键两次按下两次抬起
        private void showKey()
        {
            IntPtr Revit = Autodesk.Windows.ComponentManager.ApplicationWindow;
            SetForegroundWindow(Revit);
            keybd_event(0x1B, 0, 0, 0);
            keybd_event(0x1B, 0, 2, 0);
            keybd_event(0x1B, 0, 0, 0);
            keybd_event(0x1B, 0, 2, 0);
        }

    }

    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
    public class CalcCommand : IExternalCommand
    {

        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            TaskDialog.Show("Dummy command", "This is a dummy command for buttons associated to contextual help.");
            return Result.Succeeded;
        }
    }
}
